# -*- coding: utf-8 -*-

import numpy as np
from datetime import datetime
import wave
import time
import urllib, urllib2, pycurl
import base64
import json
import os
import sys
import MySQLdb as mdb
import RPi.GPIO as GPIO

reload(sys)
sys.setdefaultencoding( "utf-8" )

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
GPIO.setup(13,GPIO.IN)
GPIO.output(11,GPIO.HIGH)

save_count = 0
save_buffer = []
t = 0
sum = 0
time_flag = 0
flag_num = 0
filename = 'asr.wav'
commun = '1'
answer = '1'
def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    return html

def get_token():
    apiKey = "hfglIjjqGXmhyu7kGL31Mwzt"
    secretKey = "5a724c83d98acbf8cf8dec032eb49438"
    auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;
    res = urllib2.urlopen(auth_url)
    json_data = res.read()
    return json.loads(json_data)['access_token']

def dump_res(buf):
    global commun
    print "字符串类型"
    print (buf)
    a = eval(buf)
    print type(a)
    if a['err_msg']=='success.':
        commun = a['result'][0]
        #print commun

def use_cloud(token):
    fp = wave.open(filename, 'rb')
    nf = fp.getnframes()
    f_len = nf * 2
    audio_data = fp.readframes(nf)
    cuid = "79669421" #产品id
    srv_url = 'http://vop.baidu.com/server_api' + '?cuid=' + cuid + '&token=' + token
    http_header = [
        'Content-Type: audio/pcm; rate=8000',
        'Content-Length: %d' % f_len
    ]

    c = pycurl.Curl()
    c.setopt(pycurl.URL, str(srv_url)) #curl doesn't support unicode
    #c.setopt(c.RETURNTRANSFER, 1)
    c.setopt(c.HTTPHEADER, http_header)   #must be list, not dict
    c.setopt(c.POST, 1)
    c.setopt(c.CONNECTTIMEOUT, 30)
    c.setopt(c.TIMEOUT, 30)
    c.setopt(c.WRITEFUNCTION, dump_res)
    c.setopt(c.POSTFIELDS, audio_data)
    c.setopt(c.POSTFIELDSIZE, f_len)
    c.perform() #pycurl.perform() has no return val

# 将data中的数据保存到名为filename的WAV文件中
def save_wave_file(filename, data):
    wf = wave.open(filename, 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(2)
    wf.setframerate(SAMPLING_RATE)
    wf.writeframes("".join(data))
    wf.close()

token = get_token()
key = 'f2af72c9d40b445895c0e3a1193da4a3'
api = 'http://www.tuling123.com/openapi/api?key=' + key + '&info='
row=[1,1,3]
in_value = True
num=-1
str3=""
strtemp=""
while(True):
    in_value = GPIO.input(13)
    while in_value == True:
          in_value = GPIO.input(13)
    url = "http://tsn.baidu.com/text2audio?tex="+"什么情况？"+"&lan=zh&per=0&pit=9&spd=6&cuid=8297904&ctp=1&tok=24.3bda5141e3acde6ca6685b42f655015e.2592000.1497864478.282335-9670441"
    os.system('mplayer "%s"'%(url))

    os.system('arecord -D "plughw:1,0" -f S16_LE -d 4 -r 8000 asr.wav')

    #os.system('mplayer "%s"'%(url))
    use_cloud(token)
    if commun !="":
        sStr1 = ''
        sStr2 = '关灯'
        print sStr1.find(sStr2)
        print commun+'!'
        site = commun
        if site.find("灯光")!=-1: #在返回的文本里寻找“开”
            answer = '好的，正在为您开，请稍后'
            url = "http://tsn.baidu.com/text2audio?tex="+answer+"&lan=zh&per=0&pit=9&spd=6&cuid=8297904&ctp=1&tok=24.3bda5141e3acde6ca6685b42f655015e.2592000.1497864478.282335-9670441"
            os.system('mplayer "%s"'%(url))
            GPIO.output(11,False)
        elif site.find("音乐")!=-1: #在返回的文本里寻找“开”
            url="shero.mp3"
            os.system('mplayer "%s"'%(url))
            time.sleep(3)
        elif site.find("请关灯")!=-1:
            answer = '好的，正在为您关，请稍后'
            url = "http://tsn.baidu.com/text2audio?tex="+answer+"&lan=zh&per=0&pit=9&spd=6&cuid=8297904&ctp=1&tok=24.3bda5141e3acde6ca6685b42f655015e.2592000.1497864478.282335-9670441"
            os.system('mplayer "%s"'%(url))
            GPIO.output(11,True)
        elif site.find("打开下一页")!=-1: #在返回的文本里寻找
            answer = '好的，正在为您打开，请稍后'
            url = "http://tsn.baidu.com/text2audio?tex="+answer+"&lan=zh&per=0&pit=9&spd=6&cuid=8297904&ctp=1&tok=24.3bda5141e3acde6ca6685b42f655015e.2592000.1497864478.282335-9670441"
            os.system('mplayer "%s"'%(url))
        #连接 mysql，获取连接的对象
            con = mdb.connect('localhost', 'root', 'patrickben66.', 'MyFirstDatase',charset='utf8')
            with con:
                cur = con.cursor()
        # 创建一个数据表 writers(id,name)
                cur.execute("SELECT * FROM WebPage where Id=15")
        #使用 fetchall 函数，将结果集（多维元组）存入 rows 里面
                row = cur.fetchall()
        # 加一
		cur.execute("update WebPage set WebP=%d where Id=15"%(int(row[0][1])+1))
        elif site.find("返回")!=-1: #在返回的文本里寻找“返回上一页"”
            answer = '好的，正在为您返回，请稍后'
            url = "http://tsn.baidu.com/text2audio?tex="+answer+"&lan=zh&per=0&pit=9&spd=6&cuid=8297904&ctp=1&tok=24.3bda5141e3acde6ca6685b42f655015e.2592000.1497864478.282335-9670441"
            os.system('mplayer "%s"'%(url))
        #连接 mysql，获取连接的对象
            con = mdb.connect('localhost', 'root', 'patrickben66.', 'MyFirstDatase',charset='utf8')
            with con:
                cur = con.cursor()
        # 创建一个数据表 writers(id,name)
                cur.execute("SELECT * FROM WebPage where Id=15")
        #使用 fetchall 函数，将结果集（多维元组）存入 rows 里面
		row = cur.fetchall()
		cur.execute("update WebPage set WebP=%d where Id=15"%(int(row[0][1])-1))

        elif site.find("百度一下")!=-1: #在返回的文本里寻找
            num=site.find("百度一下")
            answer = '好的，正在为您，请稍后'
            url = "http://tsn.baidu.com/text2audio?tex="+answer+"&lan=zh&per=0&pit=9&spd=6&cuid=8297904&ctp=1&tok=24.3bda5141e3acde6ca6685b42f655015e.2592000.1497864478.282335-9670441"
            os.system('mplayer "%s"'%(url))
        #连接 mysql，获取连接的对象
            con = mdb.connect('localhost', 'root', 'patrickben66.', 'MyFirstDatase',charset='utf8')
            with con:

        #仍然是，第一步要获取连接的 cursor 对象，用于执行查询
			cur = con.cursor()
			#cur.execute("alter table WebPage modify WebP char(50) character set gbk")
        # 创建一个数据表 writers(id,name)
	#		cur.execute("SELECT * FROM WebPage where Id=5")
        #使用 fetchall 函数，将结果集（多维元组）存入 rows 里面
	#		row = cur.fetchall()
			#print row
			#print row[1]
        # 加一

                        cur.execute("update WebPage set WebP=%d where Id=15"%(16))
                        strtemp='"'+site[num+8:]+'"'
                        str3='update WebPage set WebP='+strtemp+' where Id=16'
                        print str3
                        unicodestring =str3
                        utf8string = unicodestring.encode("utf-8")
                        print type(utf8string)
                        print str(str3)
			cur.execute(str3)
			#mdb.close()
			con.commit()


        else:
            print commun
            info = commun
            request = api   + info
            response = getHtml(request)
            dic_json = json.loads(response)

            a = dic_json['text']
            print type(a)
            unicodestring = a
            # 将Unicode转化为普通Python字符串："encode"
            utf8string = unicodestring.encode("utf-8")
            print type(utf8string)
            print str(a)
            url = "http://tsn.baidu.com/text2audio?tex="+dic_json['text']+"&lan=zh&per=0&pit=9&spd=6&cuid=8297904&ctp=1&tok=24.3bda5141e3acde6ca6685b42f655015e.2592000.1497864478.282335-9670441"
	    os.system('mplayer "%s"'%(url))

        commun=""
    time.sleep(1)
